<template>
  <component :ref="componentId" :is="data.remote" v-if="data.remote" v-bind="$attrs"> </component>
</template>
<script setup lang="ts">
import { getMaterialFormal } from '@/api/material/material-formal';
import * as Vue from 'vue';
import * as http from '@/utils/http';

import { reactive, onBeforeMount } from 'vue';
import { loadModule } from 'vue3-sfc-loader/dist/vue3-sfc-loader.js';

defineOptions({
  name: 'DwRender',
});
const componentId: never = Vue.useId() as never;
const data = reactive({
  remote: null,
  temp: '',
  options: {
    moduleCache: {
      vue: Vue,
      '@/utils/http': http,
    },
    //获取文件
    async getFile(componentName: string) {
      const identification = componentName.replace('.vue', '');
      const { data } = await getMaterialFormal(identification);
      const result = data as unknown as { content: string };
      return Promise.resolve(result.content);
    },
    //添加样式
    addStyle(textContent: string) {
      console.log(textContent);
      const style = Object.assign(document.createElement('style'), {
        textContent,
      });
      const styleRef = document.head.getElementsByTagName('style')[0] || null;
      document.head.insertBefore(style, styleRef);
    },
  },
});

const loadComponent = async (componentName: string) => {
  const component = await loadModule(componentName, data.options);
  const name = componentName.split('@')[0];
  // if (componentName != 'Form') {
  //
  // }
  data.remote = component;
  //全局安装组件
  // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  //@ts-ignore
  window.app.component(`Dwt${name}`, component);
};
onBeforeMount(async () => {
  await loadComponent('Select@0.0.1.vue');
  await loadComponent('Form@0.0.1.vue');
});
</script>
